package day9;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

import org.junit.Test;

public class ExceotionDemo {

	@Test
	public void test1() {
		int i = 3;
		// ArithmeticException: / by zero
		System.out.println(i / 0);
	}
	
	@Test
	public void test2() {
		// 编译时异常：写代码时候不处理这个异常程序直接报错无法编译
		try {// try里面包含的是可能抛出异常的代码
			FileInputStream fileInputStream = new FileInputStream("a.txt");
		} catch (FileNotFoundException e) {//如果代码抛出异常，就会跑到catch
			e.printStackTrace();
		}
		
		try {
			FileInputStream fileInputStream = new FileInputStream("a.txt");
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
	}
	
	
	@Test
	public void test3() {
		int num1 = 3;
		int num2 = 0;
		System.out.println("----start-----");
		// 运行时异常是因为程序写的有问题，不要用try-catch去处理问题
		if (num2 != 0) {
			int result = num1 / num2;
		}
		System.out.println("----end-----");
	}
	
	@Test
	public void test4() {
		int num1 = 3;
		int num2 = 0;
		System.out.println("----start-----");
		try {// try里面包含的是可能抛出异常的代码
			System.out.println("----try-----");
			int result = num1 / num2;
		} catch (ArithmeticException e) {//如果代码抛出异常，就会跑到catch
			System.out.println("----catch-----");
			e.printStackTrace();
		} finally {
			// 一定会被执行的代码（不管异常抛不抛出都会执行）
			System.out.println("----finally----");
		}
		// 因为catch捕获了异常程序没有挂掉，后面的代码继续执行
		System.out.println("----end-----");
	}
	
	// IO：Input Output
	@Test
	public void test5() {
		try {
			FileInputStream fileInputStream = new FileInputStream("a.txt");
			fileInputStream.read();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} 
	}
	
	@Test
	public void test6() throws FileNotFoundException {
		FileInputStream fileInputStream = new FileInputStream("a.txt");
	}
	
	
	public static void main(String[] args) {
		try {
			fun();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		
		try {
			fun2();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
	}

	// 编译时异常可以不处理，throws抛出
	private static void fun() throws FileNotFoundException {
		//  throw new FileNotFoundException("Invalid file path");
		FileInputStream fileInputStream = new FileInputStream("a.txt");
	}
	
	public static void fun2() throws FileNotFoundException  {
		// 这个文件找不到了，可以手动抛出一个异常
		throw new FileNotFoundException("文件找不到");
	}
	
	@Test
	public void test66() {
		AccountManger accountManger = new AccountManger(100.0, 1);
		accountManger.doposite(100.0);
		try {
			accountManger.withdraw(300.0);
		} catch (MeiQianException e) {
			e.printStackTrace();
		}
		System.out.println("---------------");
	}
	
}
